var config = require("../config.js");
var $ = require("./deferred.js")
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
const formatDay = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return [year, month, day].map(formatNumber).join('-')
}
const appendUrlParams = (url, params) => {
  var paramStr = "";
  for (var i in params) {
    if (paramStr !== "") {
      paramStr += "&";
    }
    paramStr += encodeURIComponent(i) + "=" + encodeURIComponent(params[i]);
  }
  if (paramStr == "") {
    return url;
  } else {
    return url + (url.indexOf("?") >= 0 ? "&" : "?") + paramStr;
  }
}
const showErrorMsgDialog=(msg,title)=>{
  var dtd = $.Deferred();
  wx.showModal({
    title: title||'提示',
    content: msg,
    showCancel: false,
    success: function (res) {
      if (res.confirm) {
        console.log('showErrorMsgDialog点击了确定');
      }
    },
    complete:function(res){
      console.log("showErrorMsgDialog完成...");
      dtd.resolve(res);
    }
  });
}
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
const ajax = (opts, promise) => {
  var host = config.host;
  var protocol = config.protocol;
  var url = opts.url;
  //如果url不带http或者https，则自动加上{protocol}://{host}
  if (url.substr(0, protocol.length) !== protocol) {
    if (url.substr(0, 1) !== "/") {
      url = "/" + url;
    }
    url = protocol + "//" + host + url;
  }
  opts.url = url;

  var dtd = $.Deferred();

  //在连接后面加上随机数
  var randomStr = (opts.url.indexOf("?") >= 0 ? "&" : "?") + "rnd_rnd_rnd=" + new Date().getTime();
  opts.url = opts.url + randomStr;
  var method = opts.method ? opts.method : "GET";
  //发请求
  wx.request({
    url: opts.url,
    data: opts.data,
    method: method,
    success: (data) => {
      if (data.data.errorCode && data.data.errorCode != "0") {
        dtd.reject(data.data);
      }
      dtd.resolve(data.data);
    },
    fail: (data) => {
      dtd.reject(data);
    },
    complete: () => {
      //wx.hideLoading();
    }
  });
  return dtd;
}

module.exports = {
  formatDay: formatDay,
  formatTime: formatTime,
  appendUrlParams: appendUrlParams,
  ajax: ajax,
  showErrorMsgDialog: showErrorMsgDialog
}
